<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>nodejs系列之express | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Node,Express,">
  

  <meta name="description" content="一、概述 官网 http://expressjs.com/zh-cn/   Express是目前最流行的基于Node.js的Web开发框架，可以快速地搭建一个完整功能的网站  环境搭建  http://www.expressjs.com.cn/starter/generator.html   通过应用生成器工具 express-generator可以快速创建一个应用的骨架  $ npm insta">
<meta name="keywords" content="Node,Express">
<meta property="og:type" content="article">
<meta property="og:title" content="nodejs系列之express">
<meta property="og:url" content="http://blog.poetries.top/2018/12/23/express/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、概述 官网 http://expressjs.com/zh-cn/   Express是目前最流行的基于Node.js的Web开发框架，可以快速地搭建一个完整功能的网站  环境搭建  http://www.expressjs.com.cn/starter/generator.html   通过应用生成器工具 express-generator可以快速创建一个应用的骨架  $ npm insta">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.906Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nodejs系列之express">
<meta name="twitter:description" content="一、概述 官网 http://expressjs.com/zh-cn/   Express是目前最流行的基于Node.js的Web开发框架，可以快速地搭建一个完整功能的网站  环境搭建  http://www.expressjs.com.cn/starter/generator.html   通过应用生成器工具 express-generator可以快速创建一个应用的骨架  $ npm insta">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、概述"><span class="toc-text">一、概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、运行原理"><span class="toc-text">二、运行原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、use方法"><span class="toc-text">三、use方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、Express的方法"><span class="toc-text">四、Express的方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、set方法"><span class="toc-text">五、set方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、response对象"><span class="toc-text">六、response对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、requst对象"><span class="toc-text">七、requst对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、搭建HTTPs服务器"><span class="toc-text">八、搭建HTTPs服务器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、静态网页模板"><span class="toc-text">九、静态网页模板</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十、动态网页模板"><span class="toc-text">十、动态网页模板</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十一、新建数据脚本"><span class="toc-text">十一、新建数据脚本</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十二、新建网页模板"><span class="toc-text">十二、新建网页模板</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十三、渲染模板"><span class="toc-text">十三、渲染模板</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十四、指定静态文件目录"><span class="toc-text">十四、指定静态文件目录</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十五、Express-Router用法"><span class="toc-text">十五、Express.Router用法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十六、router-route方法"><span class="toc-text">十六、router.route方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十七、router中间件"><span class="toc-text">十七、router中间件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十八、对路径参数的处理"><span class="toc-text">十八、对路径参数的处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十九、app-route"><span class="toc-text">十九、app.route</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二十、上传文件"><span class="toc-text">二十、上传文件</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-express" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">nodejs系列之express</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.12.23</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Back-End/">Back-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 3.7k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 16分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h2><blockquote>
<p>官网 <a href="http://expressjs.com/zh-cn/" target="_blank" rel="noopener">http://expressjs.com/zh-cn/</a></p>
</blockquote>
<blockquote>
<p><code>Express</code>是目前最流行的基于Node.js的Web开发框架，可以快速地搭建一个完整功能的网站</p>
</blockquote>
<p><strong>环境搭建</strong></p>
<blockquote>
<p><a href="http://www.expressjs.com.cn/starter/generator.html" target="_blank" rel="noopener">http://www.expressjs.com.cn/starter/generator.html</a></p>
</blockquote>
<blockquote>
<p>通过应用生成器工具 <code>express-generator</code>可以快速创建一个应用的骨架</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install express-generator -g</span><br></pre></td></tr></table></figure>
<h2 id="二、运行原理"><a href="#二、运行原理" class="headerlink" title="二、运行原理"></a>二、运行原理</h2><p><strong>底层：http模块</strong></p>
<blockquote>
<p>Express框架建立在node.js内置的http模块上。http模块生成服务器的原始代码如下</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> app = http.createServer(<span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">  response.end(<span class="string">"Hello world!"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">3000</span>, <span class="string">"localhost"</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Express框架的核心是对http模块的再包装。上面的代码用Express改写如下</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'Hello world!'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Express框架等于在http模块之上，加了一个中间层</p>
</blockquote>
<p><strong>什么是中间件</strong></p>
<blockquote>
<ul>
<li>简单说，中间件（middleware）就是处理HTTP请求的函数。它最大的特点就是，一个中间件处理完，再传递给下一个中间件。App实例在运行过程中，会调用一系列的中间件</li>
<li>每个中间件可以从App实例，接收三个参数，依次为request对象（代表HTTP请求）、response对象（代表HTTP回应），next回调函数（代表下一个中间件）。每个中间件都可以对HTTP请求（request对象）进行加工，并且决定是否调用next方法，将request对象再传给下一个中间件。</li>
</ul>
</blockquote>
<ul>
<li>一个不进行任何操作、只传递<code>request</code>对象的中间件，就是下面这样</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uselessMiddleware</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">  next();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>上面代码的next就是下一个中间件。如果它带有参数，则代表抛出一个错误，参数为错误文本</li>
<li>抛出错误以后，后面的中间件将不再执行，直到发现一个错误处理函数为止</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uselessMiddleware</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">  next(<span class="string">'出错了！'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="三、use方法"><a href="#三、use方法" class="headerlink" title="三、use方法"></a>三、use方法</h2><blockquote>
<p>use是express注册中间件的方法，它返回一个函数。下面是一个连续调用两个中间件的例子</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">"express"</span>);</span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">request, response, next</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"In comes a "</span> + request.method + <span class="string">" to "</span> + request.url);</span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123; <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> &#125;);</span><br><span class="line">  response.end(<span class="string">"Hello world!\n"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">http.createServer(app).listen(<span class="number">1337</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面代码使用app.use方法，注册了两个中间件。收到HTTP请求后，先调用第一个中间件，在控制台输出一行信息，然后通过next方法，将执行权传给第二个中间件，输出HTTP回应。由于第二个中间件没有调用next方法，所以request对象就不再向后传递了</p>
</blockquote>
<ul>
<li>use方法内部可以对访问路径进行判断，据此就能实现简单的路由，根据不同的请求网址，返回不同的网页内容</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">"express"</span>);</span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">request, response, next</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (request.url == <span class="string">"/"</span>) &#123;</span><br><span class="line">    response.writeHead(<span class="number">200</span>, &#123; <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> &#125;);</span><br><span class="line">    response.end(<span class="string">"Welcome to the homepage!\n"</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    next();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">request, response, next</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (request.url == <span class="string">"/about"</span>) &#123;</span><br><span class="line">    response.writeHead(<span class="number">200</span>, &#123; <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> &#125;);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    next();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.writeHead(<span class="number">404</span>, &#123; <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> &#125;);</span><br><span class="line">  response.end(<span class="string">"404 error!\n"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">http.createServer(app).listen(<span class="number">1337</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面代码通过<code>request.url</code>属性，判断请求的网址，从而返回不同的内容。注意，<code>app.use</code>方法一共登记了三个中间件，只要请求路径匹配，就不会将执行权交给下一个中间件。因此，最后一个中间件会返回<code>404</code>错误，即前面的中间件都没匹配请求路径，找不到所要请求的资源</p>
</blockquote>
<ul>
<li>除了在回调函数内部判断请求的网址，<code>use</code>方法也允许将请求网址写在第一个参数。这代表，只有请求路径匹配这个参数，后面的中间件才会生效。无疑，这样写更加清晰和方便</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 只对根目录的请求，调用某个中间件</span></span><br><span class="line">app.use(<span class="string">'/path'</span>, someMiddleware);</span><br></pre></td></tr></table></figure>
<ul>
<li>因此，上面的代码可以写成下面的样子</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">ar express = require(&quot;express&quot;);</span><br><span class="line">var http = require(&quot;http&quot;);</span><br><span class="line"></span><br><span class="line">var app = express();</span><br><span class="line"></span><br><span class="line">app.use(&quot;/home&quot;, function(request, response, next) &#123;</span><br><span class="line">  response.writeHead(200, &#123; &quot;Content-Type&quot;: &quot;text/plain&quot; &#125;);</span><br><span class="line">  response.end(&quot;Welcome to the homepage!\n&quot;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(&quot;/about&quot;, function(request, response, next) &#123;</span><br><span class="line">  response.writeHead(200, &#123; &quot;Content-Type&quot;: &quot;text/plain&quot; &#125;);</span><br><span class="line">  response.end(&quot;Welcome to the about page!\n&quot;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(function(request, response) &#123;</span><br><span class="line">  response.writeHead(404, &#123; &quot;Content-Type&quot;: &quot;text/plain&quot; &#125;);</span><br><span class="line">  response.end(&quot;404 error!\n&quot;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">http.createServer(app).listen(1337)</span><br></pre></td></tr></table></figure>
<h2 id="四、Express的方法"><a href="#四、Express的方法" class="headerlink" title="四、Express的方法"></a>四、Express的方法</h2><p><strong>all方法和HTTP动词方法</strong></p>
<blockquote>
<p>针对不同的请求，Express提供了use方法的一些别名。比如，上面代码也可以用别名的形式来写</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">"express"</span>);</span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line">app.all(<span class="string">"*"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">request, response, next</span>) </span>&#123;</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123; <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> &#125;);</span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">"/"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.end(<span class="string">"Welcome to the homepage!"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">"/about"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.end(<span class="string">"Welcome to the about page!"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">"*"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  response.end(<span class="string">"404!"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">http.createServer(app).listen(<span class="number">1337</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<ul>
<li>上面代码的all方法表示，所有请求都必须通过该中间件，参数中的“*”表示对所有路径有效。get方法则是只有GET动词的HTTP请求通过该中间件，它的第一个参数是请求的路径。由于get方法的回调函数没有调用next方法，所以只要有一个中间件被调用了，后面的中间件就不会再被调用了</li>
<li>除了get方法以外，Express还提供post、put、delete方法，即HTTP动词都是Express的方法</li>
</ul>
</blockquote>
<ul>
<li>除了get方法以外，Express还提供post、put、delete方法，即HTTP动词都是Express的方法</li>
<li>这些方法的第一个参数，都是请求的路径。除了绝对匹配以外，Express允许模式匹配</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">app.get(<span class="string">"/hello/:who"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.end(<span class="string">"Hello, "</span> + req.params.who + <span class="string">"."</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="五、set方法"><a href="#五、set方法" class="headerlink" title="五、set方法"></a>五、set方法</h2><blockquote>
<p>set方法用于指定变量的值</p>
</blockquote>
<ul>
<li>使用set方法，为系统变量“views”和“view engine”指定值<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">app.set(<span class="string">"views"</span>, __dirname + <span class="string">"/views"</span>);</span><br><span class="line"></span><br><span class="line">app.set(<span class="string">"view engine"</span>, <span class="string">"jade"</span>);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="六、response对象"><a href="#六、response对象" class="headerlink" title="六、response对象"></a>六、response对象</h2><p><strong>（1）response.redirect方法</strong></p>
<blockquote>
<p>response.redirect方法允许网址的重定向</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">response.redirect(<span class="string">"/hello/anime"</span>);</span><br><span class="line">response.redirect(<span class="string">"http://www.example.com"</span>);</span><br><span class="line">response.redirect(<span class="number">301</span>, <span class="string">"http://www.example.com"</span>);</span><br></pre></td></tr></table></figure>
<p><strong>（2）response.sendFile方法</strong></p>
<blockquote>
<p>response.sendFile方法用于发送文件</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">response.sendFile(<span class="string">"/path/to/anime.mp4"</span>);</span><br></pre></td></tr></table></figure>
<p><strong>（3）response.render方法</strong></p>
<blockquote>
<p>response.render方法用于渲染网页模板。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">//  使用render方法，将message变量传入index模板，渲染成HTML网页</span><br><span class="line">app.get(&quot;/&quot;, function(request, response) &#123;</span><br><span class="line">  response.render(&quot;index&quot;, &#123; message: &quot;Hello World&quot; &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="七、requst对象"><a href="#七、requst对象" class="headerlink" title="七、requst对象"></a>七、requst对象</h2><p><strong>（1）request.ip</strong></p>
<blockquote>
<p>request.ip属性用于获得HTTP请求的IP地址</p>
</blockquote>
<p><strong>（2）request.files</strong></p>
<blockquote>
<p>request.files用于获取上传的文件</p>
</blockquote>
<h2 id="八、搭建HTTPs服务器"><a href="#八、搭建HTTPs服务器" class="headerlink" title="八、搭建HTTPs服务器"></a>八、搭建HTTPs服务器</h2><blockquote>
<p>使用Express搭建HTTPs加密服务器，也很简单</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">var</span> options = &#123;</span><br><span class="line">  key: fs.readFileSync(<span class="string">'E:/ssl/myserver.key'</span>),</span><br><span class="line">  cert: fs.readFileSync(<span class="string">'E:/ssl/myserver.crt'</span>),</span><br><span class="line">  passphrase: <span class="string">'1234'</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> https = <span class="built_in">require</span>(<span class="string">'https'</span>);</span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>)</span>&#123;</span><br><span class="line">  res.send(<span class="string">'Hello World Expressjs'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> server = https.createServer(options, app);</span><br><span class="line">server.listen(<span class="number">8084</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'Server is running on port 8084'</span>);</span><br></pre></td></tr></table></figure>
<h2 id="九、静态网页模板"><a href="#九、静态网页模板" class="headerlink" title="九、静态网页模板"></a>九、静态网页模板</h2><blockquote>
<ul>
<li>在项目目录之中，建立一个子目录views，用于存放网页模板</li>
<li>假定这个项目有三个路径：根路径（/）、自我介绍（/about）和文章（/article）。那么，app.js可以这样写</li>
</ul>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 向服务器发送信息的方法，从send变成了sendfile，后者专门用于发送文件</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   res.sendfile(<span class="string">'./views/index.html'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/about'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   res.sendfile(<span class="string">'./views/about.html'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/article'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   res.sendfile(<span class="string">'./views/article.html'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
<h2 id="十、动态网页模板"><a href="#十、动态网页模板" class="headerlink" title="十、动态网页模板"></a>十、动态网页模板</h2><p><strong>安装模板引擎</strong></p>
<blockquote>
<p>Express支持多种模板引擎，这里采用Handlebars模板引擎的服务器端版本hbs模板引擎</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">npm install hbs --save-dev</span><br></pre></td></tr></table></figure>
<ul>
<li>安装模板引擎之后，就要改写app.js</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.js文件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 加载hbs模块</span></span><br><span class="line"><span class="keyword">var</span> hbs = <span class="built_in">require</span>(<span class="string">'hbs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定模板文件的后缀名为html</span></span><br><span class="line">app.set(<span class="string">'view engine'</span>, <span class="string">'html'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 运行hbs模块</span></span><br><span class="line">app.engine(<span class="string">'html'</span>, hbs.__express);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>)</span>&#123;</span><br><span class="line">	res.render(<span class="string">'index'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/about'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">	res.render(<span class="string">'about'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/article'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">	res.render(<span class="string">'article'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面代码改用render方法，对网页模板进行渲染。render方法的参数就是模板的文件名，默认放在子目录views之中，后缀名已经在前面指定为html，这里可以省略。所以，res.render(‘index’) 就是指，把子目录views下面的index.html文件，交给模板引擎hbs渲染</p>
</blockquote>
<h2 id="十一、新建数据脚本"><a href="#十一、新建数据脚本" class="headerlink" title="十一、新建数据脚本"></a>十一、新建数据脚本</h2><blockquote>
<ul>
<li>渲染是指将数据代入模板的过程。实际运用中，数据都是保存在数据库之中的，这里为了简化问题，假定数据保存在一个脚本文件中</li>
<li>在项目目录中，新建一个文件blog.js，用于存放数据。blog.js的写法符合CommonJS规范，使得它可以被require语句加载</li>
</ul>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// blog.js文件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> entries = [</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">1</span>, <span class="string">"title"</span>:<span class="string">"第一篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/2/2013"</span>&#125;,</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">2</span>, <span class="string">"title"</span>:<span class="string">"第二篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/3/2013"</span>&#125;,</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">3</span>, <span class="string">"title"</span>:<span class="string">"第三篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/4/2013"</span>&#125;,</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">4</span>, <span class="string">"title"</span>:<span class="string">"第四篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/5/2013"</span>&#125;,</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">5</span>, <span class="string">"title"</span>:<span class="string">"第五篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/10/2013"</span>&#125;,</span><br><span class="line">	&#123;<span class="string">"id"</span>:<span class="number">6</span>, <span class="string">"title"</span>:<span class="string">"第六篇"</span>, <span class="string">"body"</span>:<span class="string">"正文"</span>, <span class="string">"published"</span>:<span class="string">"6/12/2013"</span>&#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line">exports.getBlogEntries = <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="keyword">return</span> entries;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">exports.getBlogEntry = <span class="function"><span class="keyword">function</span> (<span class="params">id</span>)</span>&#123;</span><br><span class="line">   <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>; i &lt; entries.length; i++)&#123;</span><br><span class="line">      <span class="keyword">if</span>(entries[i].id == id) <span class="keyword">return</span> entries[i];</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="十二、新建网页模板"><a href="#十二、新建网页模板" class="headerlink" title="十二、新建网页模板"></a>十二、新建网页模板</h2><blockquote>
<p>接着，新建模板文件<code>index.html</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;!-- views/index.html文件 --&gt;</span><br><span class="line"></span><br><span class="line">&lt;h1&gt;文章列表&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp"> </span></span><br><span class="line"><span class="regexp">&#123;&#123;#each entries&#125;&#125;</span></span><br><span class="line"><span class="regexp">   &lt;p&gt;</span></span><br><span class="line"><span class="regexp">      &lt;a href="/</span>article/&#123;&#123;id&#125;&#125;<span class="string">"&gt;&#123;&#123;title&#125;&#125;&lt;/a&gt;&lt;br/&gt;</span></span><br><span class="line"><span class="string">      Published: &#123;&#123;published&#125;&#125;</span></span><br><span class="line"><span class="string">   &lt;/p&gt;</span></span><br><span class="line"><span class="string">&#123;&#123;/each&#125;&#125;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;!-- views/about.html文件 --&gt;</span><br><span class="line"></span><br><span class="line">&lt;h1&gt;自我介绍&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp"> </span></span><br><span class="line"><span class="regexp">&lt;p&gt;正文&lt;/</span>p&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;!-- views/article.html文件 --&gt;</span><br><span class="line"></span><br><span class="line">&lt;h1&gt;&#123;&#123;blog.title&#125;&#125;&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">Published: &#123;&#123;blog.published&#125;&#125;</span></span><br><span class="line"><span class="regexp"> </span></span><br><span class="line"><span class="regexp">&lt;p/</span>&gt;</span><br><span class="line"> </span><br><span class="line">&#123;&#123;blog.body&#125;&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>可以看到，上面三个模板文件都只有网页主体。因为网页布局是共享的，所以布局的部分可以单独新建一个文件<code>layout.html</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;!-- views/layout.html文件 --&gt;</span><br><span class="line"></span><br><span class="line">&lt;html&gt;</span><br><span class="line"> </span><br><span class="line">&lt;head&gt;</span><br><span class="line">   &lt;title&gt;&#123;&#123;title&#125;&#125;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"> </span><br><span class="line">&lt;body&gt;</span><br><span class="line"> </span><br><span class="line">	&#123;&#123;&#123;body&#125;&#125;&#125;</span><br><span class="line"> </span><br><span class="line">   &lt;footer&gt;</span><br><span class="line">      &lt;p&gt;</span><br><span class="line">         &lt;a href=<span class="string">"/"</span>&gt;首页&lt;<span class="regexp">/a&gt; - &lt;a href="/</span>about<span class="string">"&gt;自我介绍&lt;/a&gt;</span></span><br><span class="line"><span class="string">      &lt;/p&gt;</span></span><br><span class="line"><span class="string">   &lt;/footer&gt;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">&lt;/body&gt;</span></span><br><span class="line"><span class="string">&lt;/html&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="十三、渲染模板"><a href="#十三、渲染模板" class="headerlink" title="十三、渲染模板"></a>十三、渲染模板</h2><blockquote>
<p>最后，改写app.js文件</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.js文件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"> </span><br><span class="line"><span class="keyword">var</span> hbs = <span class="built_in">require</span>(<span class="string">'hbs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 加载数据模块</span></span><br><span class="line"><span class="keyword">var</span> blogEngine = <span class="built_in">require</span>(<span class="string">'./blog'</span>);</span><br><span class="line"> </span><br><span class="line">app.set(<span class="string">'view engine'</span>, <span class="string">'html'</span>);</span><br><span class="line">app.engine(<span class="string">'html'</span>, hbs.__express);</span><br><span class="line">app.use(express.bodyParser());</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   res.render(<span class="string">'index'</span>,&#123;<span class="attr">title</span>:<span class="string">"最近文章"</span>, <span class="attr">entries</span>:blogEngine.getBlogEntries()&#125;);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/about'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   res.render(<span class="string">'about'</span>, &#123;<span class="attr">title</span>:<span class="string">"自我介绍"</span>&#125;);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.get(<span class="string">'/article/:id'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">   <span class="keyword">var</span> entry = blogEngine.getBlogEntry(req.params.id);</span><br><span class="line">   res.render(<span class="string">'article'</span>,&#123;<span class="attr">title</span>:entry.title, <span class="attr">blog</span>:entry&#125;);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>上面代码中的render方法，现在加入了第二个参数，表示模板变量绑定的数据</li>
</ul>
<h2 id="十四、指定静态文件目录"><a href="#十四、指定静态文件目录" class="headerlink" title="十四、指定静态文件目录"></a>十四、指定静态文件目录</h2><blockquote>
<p>模板文件默认存放在views子目录。这时，如果要在网页中加载静态文件（比如样式表、图片等），就需要另外指定一个存放静态文件的目录</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">app.use(express.static(<span class="string">'public'</span>));</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面代码在文件app.js之中，指定静态文件存放的目录是public。于是，当浏览器发出非HTML文件请求时，服务器端就到public目录寻找这个文件。比如，浏览器发出如下的样式表请求：</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;link href=<span class="string">"/bootstrap/css/bootstrap.css"</span> rel=<span class="string">"stylesheet"</span>&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li>服务器端就到<code>public/bootstrap/css/</code>目录中寻找<code>bootstrap.css</code>文件</li>
</ul>
<h2 id="十五、Express-Router用法"><a href="#十五、Express-Router用法" class="headerlink" title="十五、Express.Router用法"></a>十五、Express.Router用法</h2><blockquote>
<p>从<code>Express 4.0</code>开始，路由器功能成了一个单独的组件<code>Express.Router</code>。它好像小型的<code>express</code>应用程序一样，有自己的<code>use</code>、<code>get</code>、<code>param</code>和<code>route</code>方法</p>
</blockquote>
<p><strong>基本用法</strong></p>
<blockquote>
<p>首先，Express.Router是一个构造函数，调用后返回一个路由器实例。然后，使用该实例的HTTP动词方法，为不同的访问路径，指定回调函数；最后，挂载到某个路径。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> router = express.Router();</span><br><span class="line"></span><br><span class="line">router.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'首页'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">router.get(<span class="string">'/about'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'关于'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">'/'</span>, router);</span><br></pre></td></tr></table></figure>
<blockquote>
<ul>
<li>上面代码先定义了两个访问路径，然后将它们挂载到根目录</li>
<li>这种路由器可以自由挂载的做法，为程序带来了更大的灵活性，既可以定义多个路由器实例，也可以为将同一个路由器实例挂载到多个路径。</li>
</ul>
</blockquote>
<h2 id="十六、router-route方法"><a href="#十六、router-route方法" class="headerlink" title="十六、router.route方法"></a>十六、router.route方法</h2><blockquote>
<p>router实例对象的route方法，可以接受访问路径作为参数</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> router = express.Router();</span><br><span class="line"></span><br><span class="line">router.route(<span class="string">'/api'</span>)</span><br><span class="line">	.post(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">		<span class="comment">// ...</span></span><br><span class="line">	&#125;)</span><br><span class="line">	.get(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">		Bear.find(<span class="function"><span class="keyword">function</span>(<span class="params">err, bears</span>) </span>&#123;</span><br><span class="line">			<span class="keyword">if</span> (err) res.send(err);</span><br><span class="line">			res.json(bears);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">'/'</span>, router);</span><br></pre></td></tr></table></figure>
<h2 id="十七、router中间件"><a href="#十七、router中间件" class="headerlink" title="十七、router中间件"></a>十七、router中间件</h2><blockquote>
<p>use方法为router对象指定中间件，即在数据正式发给用户之前，对数据进行处理。下面就是一个中间件的例子</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">router.use(<span class="function"><span class="keyword">function</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(req.method, req.url);</span><br><span class="line">	next();	</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ul>
<li>上面代码中，回调函数的next参数，表示接受其他中间件的调用。函数体中的next()，表示将数据传递给下一个中间件</li>
<li>注意，中间件的放置顺序很重要，等同于执行顺序。而且，中间件必须放在HTTP动词方法之前，否则不会执行</li>
</ul>
<h2 id="十八、对路径参数的处理"><a href="#十八、对路径参数的处理" class="headerlink" title="十八、对路径参数的处理"></a>十八、对路径参数的处理</h2><blockquote>
<p>router对象的param方法用于路径参数的处理，可以</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">router.param(<span class="string">'name'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res, next, name</span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 对name进行验证或其他处理……</span></span><br><span class="line">	<span class="built_in">console</span>.log(name);</span><br><span class="line">	req.name = name;</span><br><span class="line">	next();	</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">router.get(<span class="string">'/hello/:name'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">	res.send(<span class="string">'hello '</span> + req.name + <span class="string">'!'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面代码中，get方法为访问路径指定了name参数，param方法则是对name参数进行处理。注意，param方法必须放在HTTP动词方法之前</p>
</blockquote>
<h2 id="十九、app-route"><a href="#十九、app-route" class="headerlink" title="十九、app.route"></a>十九、app.route</h2><blockquote>
<ul>
<li>假定app是Express的实例对象，Express 4.0为该对象提供了一个route属性。app.route实际上是express.Router()的缩写形式，直接挂载到根路径</li>
<li>因此，对同一个路径指定get和post方法的回调函数，可以写成链式形式</li>
</ul>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">app.route(<span class="string">'/login'</span>)</span><br><span class="line">	.get(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">		res.send(<span class="string">'this is the login form'</span>);</span><br><span class="line">	&#125;)</span><br><span class="line">	.post(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">'processing'</span>);</span><br><span class="line">		res.send(<span class="string">'processing the login form!'</span>);</span><br><span class="line">	&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="二十、上传文件"><a href="#二十、上传文件" class="headerlink" title="二十、上传文件"></a>二十、上传文件</h2><ul>
<li>首先，在网页插入上传文件的表单</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;form action=<span class="string">"/pictures/upload"</span> method=<span class="string">"POST"</span> enctype=<span class="string">"multipart/form-data"</span>&gt;</span><br><span class="line">  Select an image to upload:</span><br><span class="line">  &lt;input type=<span class="string">"file"</span> name=<span class="string">"image"</span>&gt;</span><br><span class="line">  &lt;input type=<span class="string">"submit"</span> value=<span class="string">"Upload Image"</span>&gt;</span><br><span class="line">&lt;<span class="regexp">/form&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后，服务器脚本建立指向/upload目录的路由。这时可以安装multer模块，它提供了上传文件的许多功能</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> router = express.Router();</span><br><span class="line"><span class="keyword">var</span> multer = <span class="built_in">require</span>(<span class="string">'multer'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> uploading = multer(&#123;</span><br><span class="line">  dest: __dirname + <span class="string">'../public/uploads/'</span>,</span><br><span class="line">  <span class="comment">// 设定限制，每次最多上传1个文件，文件大小不超过1MB</span></span><br><span class="line">  limits: &#123;<span class="attr">fileSize</span>: <span class="number">1000000</span>, <span class="attr">files</span>:<span class="number">1</span>&#125;,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.post(<span class="string">'/upload'</span>, uploading, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/12/23/koa2/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/12/24/shell/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
